import tkinter as tk
from tkinter import filedialog
import pandas as pd 
import pathlib

def open_file_dialog():
    file_path = filedialog.askopenfilename(title="Select a File", filetypes=[("csv files", "*.csv"), ("All files", "*.*")])
    if file_path:
    #    str_file=(text=f"Selected File: {file_path}")
       process_file(file_path)

def process_file(file_path):
    # file='C:\\Users\\awu\\projects\\grabdata\\data.csv'
    global file_url
    file_url=pathlib.Path(file_path)
    file_path = file_url.parent
    label_filename['text']=file_url.name
    global df 
    df= pd.read_csv(file_url, header=0, parse_dates=[0], index_col=0)
    # print(df)
    #显示数据日期的最先和最后的时刻
    label1['text'] =str(df.index[0])
    label2['text'] =str(df.index[-1])
    print(df)

def grab_data():
    global file_url
    global df
    time_end=data_endTime_in.get()
    time_begin=data_startTime_in.get()
    df = df.between_time(time_begin, time_end)
    print(df)
    # 计算平均值
    average_serial = df.mean()
    aver_df=average_serial.to_frame().T
    aver_df.insert(0, 'time_begin', time_begin)
    aver_df.insert(1, 'time_end', time_end)
    # 路径和文件名合并，生成新文件
    file_suffix_name='_average.csv'
    file_save_name=file_url.parent/(file_url.stem+file_suffix_name)
    # print(file_save_name)
    aver_df.to_csv(file_save_name)


root = tk.Tk()
root.title("数据抓取")
file_url=pathlib.Path()
df=pd.DataFrame()
open_button = tk.Button(root, text="选择文件...", command=open_file_dialog)
open_button.grid(row=0,column=1,padx=10,pady=10)
label_filename = tk.Label(root,text="文件名",fg="red")
label_filename.grid(row=0,column=2,pady=10)
grab_button = tk.Button(root, text="输入日期后计算", command=grab_data)
grab_button.grid(row=0,column=3,padx=10,pady=10)

label1 = tk.Label(root,text="文件起始时间<",fg="red")
label1.grid(row=1,column=1,padx=10,pady=10)
data_startTime_in = tk.Entry(root)
data_startTime_in.grid(row=1,column=2,padx=10,pady=10)

label2 = tk.Label(root,text="文件结束时间>",fg="red")
label2.grid(row=2,column=1,padx=10,pady=10)
data_endTime_in = tk.Entry(root)
data_endTime_in.grid(row=2,column=2,padx=10,pady=10)



root.mainloop()